package main

import (
	"database/sql"
	"fmt"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

type User struct {
	ID           uint
	Name         string
	Email        *string
	Age          uint8
	Birthday     *time.Time
	MemberNumber sql.NullString
	ActivatedAt  sql.NullTime
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

func main() {
	dsn := "root:root@tcp(192.168.4.111:3306)/mytest?charset=utf8mb4&parseTime=True&loc=Local"

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		fmt.Println("err", err)
	}

	_ = db.AutoMigrate(&User{})

	// 新增数据
	t := time.Now()
	var user = &User{
		Name:     "Anderson",
		Age:      25,
		Birthday: &t,
	}
	res := db.Create(&user)

	fmt.Println("user.ID", user.ID)
	fmt.Println("res.Error", res.Error)
	fmt.Println("res.RowsAffected", res.RowsAffected)

	// 更新单个字段
	/**
	db.Model(&User{ID: 1}).Update("age", 22)
	*/

	// 更新多个字段
	// db.Model(&User{ID: 1}).Update("age", 22)

	// 更新多个字段
	//email := "741883227@qq.com"
	//db.Model(&User{ID: 1}).Updates(&User{
	//	Age:   18,
	//	Email: &email,
	//})
}
